﻿using SiteApp.BLL.Interface;
using SiteApp.DAL;
using SiteApp.Model;
using System;
using System.Collections.Generic;
using System.Linq;

namespace SiteApp.BLL
{
    public class SiteService : ISiteService
    {
        public List<Device> UserSite(string userId)
        {

            var data = SqlDBHelper.Query<Device>($"select  c.* from [UserSite] as a left join  [Site] as b on a.SiteId = b.SID   left join [Device] as c  on b.SID = c.SiteId where   a.[UserId]='{userId}' and  b.Isenable=1");

            return data;
        }

        public List<Police> Police(string userId)
        {


            var siteList = new List<Site>();//站点信息
            var list = new List<PointDetails>();//设备数据信息
            var result = new List<Police>();//报警信息

            var device = SqlDBHelper.Query<Device,Site, Device>($"select  c.*,b.* from [UserSite] as a left join  [Site] as b on a.SiteId = b.SID   left join [Device] as c  on b.SID = c.SiteId  where   a.[UserId]='{userId}' and  b.Isenable=1",
            (SqlPoint, site) =>
                    {
                    siteList.Add(site);
                    return SqlPoint;
                    },
           splitOn: "SID").ToList();//设备信息
            var data = SqlDBHelper.Query<SqlPoint>($"select * from Point where [DeviceId] in @DeviceId ", new { @DeviceId = device.Select(a=>a.SID).ToList() });

            if (!string.IsNullOrWhiteSpace(userId))
            {
                if (data != null && data.Count > 0)
                {
                    if (data.Where(a => a.Type == 1).Count() > 0)
                    {
                        var idList = data.Where(a => a.Type == 1).Select(a => a.SID).ToList();
                        var temperature = SqlDBHelper.Query<PointDetails>($"select * from PointForTemperature where [PointId] in @Point ", new { @Point = idList });
                        
                        var group = temperature.GroupBy(a => a.PointId).Select(a=>new { 
                        key=a.Key,
                        list=a.ToList()

                        });
                        foreach (var item in group)
                        {
                         list.Add(item.list.OrderByDescending(a => a.CREATETIME).FirstOrDefault());
                        }
              
                    }

                    if (data.Where(a => a.Type == 2).Count() > 0)
                    {
                        var idList = data.Where(a => a.Type == 2).Select(a => a.SID).ToList();
                        var sf6 = SqlDBHelper.Query<PointDetails>($"select * from PointForSF6 where [PointId] in @Point ", new { @Point = idList });


                        var group = sf6.GroupBy(a => a.PointId).Select(a => new {
                            key = a.Key,
                            list = a.ToList()

                        });
                        foreach (var item in group)
                        {
                            list.Add(item.list.OrderByDescending(a => a.CREATETIME).FirstOrDefault());
                        }
                    }

                    if (data.Where(a => a.Type == 3).Count() > 0)
                    {
                        var idList = data.Where(a => a.Type == 3).Select(a => a.SID).ToList();
                        var infrared = SqlDBHelper.Query<PointDetails>($"select * from PointForInfrared where [PointId] in @Point ", new { @Point = idList });
                        
                        var group = infrared.GroupBy(a => a.PointId).Select(a => new {
                            key = a.Key,
                            list = a.ToList()

                        });
                        foreach (var item in group)
                        {
                            list.Add(item.list.OrderByDescending(a => a.CREATETIME).FirstOrDefault());
                        }
                    }
                }
            }

            if (list != null && list.Count > 0)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    var searPoint = data.Where(a => a.SID == Convert.ToInt32(list[i].PointId)).FirstOrDefault();

                    var searchStie = device.Where(a => a.SID == Convert.ToInt32(searPoint.DeviceId)).FirstOrDefault();

                    var model = new Police();
                    model.SiteName = searchStie.Name;
                    model.Voltage = searPoint.Voltage;
                    model.Name = searPoint.Name;
                    model.Point = searPoint.Point;
                    model.Createtime = list[i].CREATETIME;

                  

                    //报警筛选
                    if (searPoint.Type==1)
                    {
                        var TemperatureMax = AppConfigurtaionServices.Configuration.GetSection("Temperature:Max").Value;
                        var TemperatureMin = AppConfigurtaionServices.Configuration.GetSection("Temperature:Min").Value;

                        var HumidityMax = AppConfigurtaionServices.Configuration.GetSection("Humidity:Max").Value;
                        var HumidityMin = AppConfigurtaionServices.Configuration.GetSection("Humidity:Min").Value;
                        if (Convert.ToDouble(list[i].Temperature) >= Convert.ToDouble(TemperatureMax))
                        {
                            model.Message = $"该设备温度超过预设临界值；当前为：{list[i].Temperature}°C，预设最大临界值为：{TemperatureMax}°C。";
                            result.Add(model);
                        }
                        if (Convert.ToDouble(list[i].Temperature) < Convert.ToDouble(TemperatureMin))
                        {
                            model.Message = $"该设备温度低于预设临界值；当前为：{list[i].Temperature}°C，预设最小临界值为：{TemperatureMin}°C。";
                            result.Add(model);
                        }
                        if (Convert.ToDouble(list[i].Humidity) >= Convert.ToDouble(HumidityMax))
                        {
                            model.Message = $"该设备湿度超过预设临界值；当前为：{list[i].Humidity}°C，预设最大临界值为：{HumidityMax}°C。";
                            result.Add(model);
                        }
                        if (Convert.ToDouble(list[i].Humidity) < Convert.ToDouble(HumidityMin))
                        {
                            model.Message = $"该设备湿度低于预设临界值；当前为：{list[i].Humidity}°C，预设最小临界值为：{HumidityMin}°C。";
                            result.Add(model);
                        }
                    }
                    if (searPoint.Type == 2)
                    {
                        var PressureMax = AppConfigurtaionServices.Configuration.GetSection("Pressure:Max").Value;
                        var PressureMin = AppConfigurtaionServices.Configuration.GetSection("Pressure:Min").Value;

                        var MoistureMax = AppConfigurtaionServices.Configuration.GetSection("Moisture:Max").Value;
                        var MoistureMin = AppConfigurtaionServices.Configuration.GetSection("Moisture:Min").Value;

                        list[i].Pressure =(Math.Round(Convert.ToDouble(list[i].Pressure) / 1000, 2) - 1).ToString();
                        list[i].Moisture = Math.Round(Convert.ToDouble(list[i].Moisture) / 1000, 2).ToString();

                        if (Convert.ToDouble(list[i].Pressure) >= Convert.ToDouble(PressureMax))
                        {
                            model.Message = $"该设备压力超过预设临界值；当前为：{list[i].Pressure}压力/bar(20℃)，预设最大临界值为：{PressureMax}压力/bar(20℃)。";
                            result.Add(model);
                        }
                        if (Convert.ToDouble(list[i].Pressure) < Convert.ToDouble(PressureMin))
                        {
                            model.Message = $"该设备压力低于预设临界值；当前为：{list[i].Pressure}压力/bar(20℃)，预设最小临界值为：{PressureMin}压力/bar(20℃)。";
                            result.Add(model);
                        }
                        if (Convert.ToDouble(list[i].Moisture) >= Convert.ToDouble(MoistureMax))
                        {
                            model.Message = $"该设备湿度超过预设临界值；当前为：{list[i].Moisture}微水/ppm(20℃)，预设最大临界值为：{MoistureMax}微水/ppm(20℃)。";
                            result.Add(model);
                        }
                        if (Convert.ToDouble(list[i].Moisture) < Convert.ToDouble(MoistureMin))
                        {
                            model.Message = $"该设备湿度低于预设临界值；当前为：{list[i].Moisture}微水/ppm(20℃)，预设最小临界值为：{MoistureMin}微水/ppm(20℃)。";
                            result.Add(model);
                        }

                    }

                  
                }
            }

            return result;

        }


        public List<Site> GetAllSite(string userId)
        {
            var data = SqlDBHelper.Query<Site>($" SELECT b.*  FROM [SiteApp].[dbo].[UserSite] as a   inner join [site] as b  on a.SiteId = b.SID where a.UserId = '{userId}' and b.Isenable = 1");

            return data;

        }

        public List<Device> GetAllDevice(string siteId)
        {
            var data = SqlDBHelper.Query<Device>($"select   * from [Device]  where   [SiteId]='{siteId}' and  Isenable=1");
            return data;
        }



    }
}
